#include <54func.h>
typedef struct shareRes_s{
    int flag;//0 没有 1->牛肉 2->酸菜
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}shareRes_t;
void *classmate1(void *arg)
{
    shareRes_t * pshareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pshareRes->mutex);
    //循环等待，知道子线程得到自己想要的资源便会跳出循环，并将标志位初始化，执行语句->死亡
    while(pshareRes->flag != 1)
    {
        printf("1 is not read!\n");
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);//当不是我想要的牛肉面的时，就加锁循环等待，直至做好
    }
    pshareRes->flag = 0;
    printf("I got 1!\n");
    pthread_mutex_unlock(&pshareRes->mutex);
    pthread_exit(NULL);
}
void *classmate2(void *arg)
{
    shareRes_t * pshareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pshareRes->mutex);
    while(pshareRes->flag != 2)
    {
        printf("2 is not read!\n");
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);//当不是我想要的牛肉面的时，就加锁循环等待，直至做好
    }
    pshareRes->flag = 0;
    printf("I got 2!\n");
    pthread_mutex_unlock(&pshareRes->mutex);
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);//初始化锁
    pthread_cond_init(&shareRes.cond,NULL);//初始化条件变量


    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,classmate1,&shareRes);
    pthread_create(&tid2,NULL,classmate2,&shareRes);

    while(1)
    {
        int i;
        scanf("%d",&i);
        printf("I producer %d\n",i);
        pthread_mutex_lock(&shareRes.mutex); 
        shareRes.flag = i;
        //pthread_cond_broadcast(&shareRes.cond);//全部出队
        pthread_cond_signal(&shareRes.cond);//单播：若是第一个给的不是同学想要的，会浪费掉
        pthread_mutex_unlock(&shareRes.mutex); 
            

    }

    pthread_join(tid1,NULL);//不接收子线程的返回值
    pthread_join(tid2,NULL);
    return 0;
}
